package com.xxhui.shaderdemo.View;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/7/12.
 */
public class ShaderTextView extends TextView {

    private Paint outRectPaint, inRectPaint;

    private LinearGradient textLinearGradient;//文字的线性梯度

    private Matrix gradientMatrix;//梯度的矩阵

    private Paint gradientPaint;//梯度的画笔

    private int viewWidth ;
    private int mTranslate;

    public ShaderTextView(Context context) {
        super(context);
        initView();
    }

    public ShaderTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    private void initView() {
        outRectPaint = new Paint();
        outRectPaint.setColor(getResources().getColor(
                android.R.color.holo_blue_light));
        outRectPaint.setStyle(Paint.Style.FILL);
        inRectPaint = new Paint();
        inRectPaint.setColor(Color.YELLOW);
        inRectPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 绘制外层矩形
        canvas.drawRect(
                0,
                0,
                getMeasuredWidth(),
                getMeasuredHeight(),
                outRectPaint);
        // 绘制内层矩形
        canvas.drawRect(
                10,
                10,
                getMeasuredWidth() - 10,
                getMeasuredHeight() - 10,
                inRectPaint);
        canvas.save();
        // 绘制文字前平移10像素
        canvas.translate(10, 0);
        // 父类完成的方法，即绘制文本
        super.onDraw(canvas);
        if(gradientMatrix!=null){
            mTranslate += viewWidth/5;
            if(mTranslate>viewWidth){
                mTranslate -= viewWidth;
            }
            gradientMatrix.setTranslate(mTranslate,0);
            textLinearGradient.setLocalMatrix(gradientMatrix);
            postInvalidateDelayed(500);
        }
        canvas.restore();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if(viewWidth==0){
            viewWidth = getMeasuredWidth();
            if(viewWidth>0){
                gradientPaint = getPaint();
                textLinearGradient = new LinearGradient(0,0,viewWidth,0,new int[]{Color.BLUE,0xffffffff,Color.BLUE},null, Shader.TileMode.CLAMP);
                gradientPaint.setShader(textLinearGradient);
                gradientMatrix = new Matrix();
            }
        }
    }
}
